"""
@Author    : ghenyar
@Time      : 2025/8/28 16:10
@File      : middleware.py
@Desc      : 后台中间件
"""

import fnmatch
from typing import Callable
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse

from app.utils.jwt import JWTUtils
from app.utils.log import LoggingUtil

# 无需验证的路由
white_url_paths = [
    "/admin/login",
    "/admin/captcha",
    "/admin/tests",
    "/admin/docs",
]

class AdminMiddleware(BaseHTTPMiddleware):
    # 日志
    logger = LoggingUtil(__name__)

    async def dispatch(self, request: Request, call_next: Callable):

        path = request.url.path
        if not any(fnmatch.fnmatch(path, pattern) for pattern in white_url_paths):
            auth_token = request.headers.get("Authorization")
            if not auth_token or not auth_token.startswith("Bearer "):
                return JSONResponse(status_code=401,
                                    content={"code": 4011, "status": -1, "message": "未授权访问或令牌已过期，请重新登录"})

            token = auth_token[len("Bearer "):]
            try:
                if JWTUtils.token_expired(token):
                    return JSONResponse(status_code=401,
                                        content={"code": 4012, "status": -1, "message": "令牌已过期，请重新登录"})
                analyze_admin_token = JWTUtils.decode_token(token)
                if not analyze_admin_token:
                    return JSONResponse(status_code=401,
                                        content={"code": 4012, "status": -1, "message": "令牌无效，请重新登录"})
                request.state.admin_id = analyze_admin_token["id"]
            except Exception as e:
                self.logger.error(str(e))
                return JSONResponse(status_code=401,
                                    content={"code": 4013, "status": -1, "message": "令牌解析异常"})
        # 处理请求
        return await call_next(request)
